from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from database.database import get_db
from core.base.api_mode import ApiResponse, api_success
from ..schemas.gen_column_schema import GenColumnCreate, GenColumnUpdate
from ..vos.gen_column_vo import GenColumnResponse
from ..services.gen_column_service import GenColumnService

router = APIRouter()


@router.post("/create", response_model=ApiResponse[GenColumnResponse])
async def create_gen_column(gen_column_data: GenColumnCreate, db: AsyncSession = Depends(get_db)):
    """创建新的代码生成列"""
    gen_column = await GenColumnService.create_gen_column(db, gen_column_data)
    return api_success(GenColumnResponse.model_validate(gen_column), msg="创建成功")


@router.get("/list/{business_id}", response_model=ApiResponse[List[GenColumnResponse]])
async def get_all_gen_columns(business_id: int, db: AsyncSession = Depends(get_db)):
    """获取指定业务的所有代码生成列"""
    gen_columns = await GenColumnService.get_all_gen_columns_by_business(db, business_id)
    return api_success([GenColumnResponse.model_validate(g) for g in gen_columns], msg="获取成功")


@router.get("/detail/{gen_column_id}", response_model=ApiResponse[GenColumnResponse])
async def get_gen_column(gen_column_id: int, db: AsyncSession = Depends(get_db)):
    """获取单个代码生成列详情"""
    gen_column = await GenColumnService.get_gen_column_by_id(db, gen_column_id)
    if not gen_column:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="代码生成列不存在")
    return api_success(GenColumnResponse.model_validate(gen_column), msg="获取成功")


@router.put("/update/{gen_column_id}", response_model=ApiResponse[GenColumnResponse])
async def update_gen_column(
    gen_column_id: int, gen_column_data: GenColumnUpdate, db: AsyncSession = Depends(get_db)
):
    """更新代码生成列"""
    gen_column = await GenColumnService.update_gen_column(db, gen_column_id, gen_column_data)
    if not gen_column:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="代码生成列不存在")
    return api_success(GenColumnResponse.model_validate(gen_column), msg="更新成功")


@router.delete("/delete/{gen_column_id}", response_model=ApiResponse[dict])
async def delete_gen_column(gen_column_id: int, db: AsyncSession = Depends(get_db)):
    """删除代码生成列"""
    success = await GenColumnService.delete_gen_column(db, gen_column_id)
    if not success:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="代码生成列不存在")
    return api_success({}, msg="删除成功")